import { queryToParams } from '../utils/index.js';
import { text } from '../utils/public.js';

// HTTP 数据处理
function httpDeal(http, success, error) {
  if (http.readyState === 4) {
    const res = JSON.parse(http.responseText);
    if (http.status === 200) {
      success(res);
    } else if (http.status === 400) {
      error(`${res.errorCode}: ${res.message}`);
    } else if (http.status === 500) {
      error('');
    }
  }
}

// http请求 - POST
export function httpPost(url, data, success, error) {
  const http = new XMLHttpRequest();
  http.onreadystatechange = function () {
    httpDeal(http, success, error);
  }

  const path = `${text.host}:${text.port}${url}`;
  http.open('POST', path, true);
  http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  http.send(queryToParams(data));
}

// http请求 - GET
export function httpGet(url, data, success, error) {
  const http = new XMLHttpRequest();
  http.onreadystatechange = function () {
    httpDeal(http, success, error);
  }

  const path = `${text.host}:${text.port}${url}?${queryToParams(data)}`;
  http.open('GET', path, true);
  http.send();
}